import json

import random

import time

from .get_rate import update_rating

from apscheduler.schedulers.background import BackgroundScheduler

from django.shortcuts import render, redirect

from django.views.decorators.csrf import csrf_exempt

from django.http import HttpResponse, JsonResponse

from User.models import Userinfo, Game, GameTag, Rating, GameComment, ClickNum

import re

from django.core.paginator import Paginator

from User.LFM import getlist, get_train

from snownlp import SnowNLP

# Create your views here.


def hello(request):
    return HttpResponse("Hello world ! ")


def train():
    rating = Rating.objects.values_list('userId', 'gameId', 'rating')
    get_train(rating)
    pass
    # lists = getlist(rating, int(request.session.get('userid')))


scheduler = BackgroundScheduler()  # 创建一个调度器对象
scheduler.add_job(func=train, trigger='interval', seconds=30)

scheduler.start()


def gameSingle(request):
    gameid = request.GET['id']
    games = Game.objects.filter(gameid=gameid)
    gamecomments = GameComment.objects.filter(gameid=gameid)
    gametags = GameTag.objects.filter(gameid=gameid)
    paginator = Paginator(gamecomments, per_page=6)
    page_num = request.GET.get('page', 1)
    if len(gamecomments) <= 6:
        is_paginated = False
    else:
        is_paginated = True
    try:
        page_num = int(page_num)
    except:
        page_num = 1
    if page_num < 1 or page_num > paginator.num_pages:
        page_num = 1
    # is_paginated = False
    gamecomments_list = paginator.get_page(page_num)
    data = pagination_function(paginator, gamecomments_list, is_paginated)

    # 获取session
    isLogin = False
    if request.session.get('isLogin'):
        isLogin = True
        phone = request.session['phone']
        password = request.session['password']
        user = Userinfo.objects.filter(phone=phone)
        userId = user.values_list('userid', flat=True)[0]
        name = user.values_list('name', flat=True)[0]
        age = user.values_list('age', flat=True)[0]
        gender = user.values_list('gender', flat=True)[0]
        profession = user.values_list('profession', flat=True)[0]

        user_click = ClickNum.objects.filter(userId=int(userId), gameId=int(gameid))
        p = user_click.count()
        if user_click.count() == 0:
            create = ClickNum(userId=userId, gameId=gameid, click=1)
            create.save()
        else:
            c_num = user_click.values('click')[0]['click']
            user_click.update(click=c_num + 1)
            pass
        update_rating(userId, int(gameid))

    return render(request, 'gameSingle.html', locals())


def ranklist(request):
    gametag = request.GET.get("tag")
    if gametag is None:
        gamerank = Game.objects.all().order_by('-grade')[:20]
        # return render(request, 'discover.html', {'games': games})
    else:
        gamerank = Game.objects.all().filter(tag__icontains=gametag).order_by('-grade')[:20]
    if len(gamerank) < 10:
        is_paginated = False
    else:
        is_paginated = True
    # 分页显示
    paginator = Paginator(gamerank, per_page=10)
    page_num = request.GET.get('page', 1)
    try:
        page_num = int(page_num)
    except:
        page_num = 1
    if page_num < 1 or page_num > paginator.num_pages:
        page_num = 1
    # is_paginated = True
    rank_list = paginator.get_page(page_num)
    data = pagination_function(paginator, rank_list, is_paginated)

    # 获取session
    isLogin = False
    if request.session.get('isLogin'):
        isLogin = True
        phone = request.session['phone']
        password = request.session['password']
        user = Userinfo.objects.filter(phone=phone)
        name = user.values_list('name', flat=True)[0]
        age = user.values_list('age', flat=True)[0]
        gender = user.values_list('gender', flat=True)[0]
        profession = user.values_list('profession', flat=True)[0]

    return render(request, 'ranklist.html', locals())


def about(request):
    # 获取session
    isLogin = False
    if request.session.get('isLogin'):
        isLogin = True
        phone = request.session['phone']
        password = request.session['password']
        user = Userinfo.objects.filter(phone=phone)
        name = user.values_list('name', flat=True)[0]
        age = user.values_list('age', flat=True)[0]
        gender = user.values_list('gender', flat=True)[0]
        profession = user.values_list('profession', flat=True)[0]
    return render(request, 'about.html', locals())


def index(request):
    ret = {}
    # 查询游戏
    n = random.randint(1, 306)
    gametags = GameTag.objects.values('tag').distinct()[n:n + 12]
    game_hero = Game.objects.all().order_by('?')[:4]
    games1 = Game.objects.all().order_by('?')[:10]
    games2 = Game.objects.all().order_by("-grade")[:10]
    ret.update(gametags=gametags, game_hero=game_hero, gamerecommends=games1, games2=games2)

    # session检查登录状态
    isLogin = False
    if request.session.get('isLogin'):
        isLogin = True
        userid = request.session['userid']
        phone = request.session['phone']
        password = request.session['password']
        user = Userinfo.objects.filter(phone=phone)
        name = user.values_list('name', flat=True)[0]
        age = user.values_list('age', flat=True)[0]
        gender = user.values_list('gender', flat=True)[0]
        profession = user.values_list('profession', flat=True)[0]
        ret.update(userid=userid, name=name, phone=phone, password=password, age=age, gender=gender,profession=profession)
        if request.session.get('remember') == 1:
            remember = 1
            ret.update(remember=remember)
            pass
        rating = Rating.objects.values_list('userId', 'gameId', 'rating')
        lists = getlist(rating, int(request.session.get('userid')))
        if lists:
            gamerecommend = []
            for i in lists:
                gamerecommend.extend((Game.objects.filter(gameid=i[0])))
                # print(Game.objects.filter(gameid=i[0])[0].name)
                pass
            ret.update(gametags=gametags, game_hero=game_hero, gamerecommends=gamerecommend)
            # 推荐信息处理完成
    ret.update(isLogin=isLogin)
    return render(request, 'index.html', ret)


# ajax登录
@csrf_exempt
def login(request):
    if request.is_ajax():
        ret = {"flag": False, "error_msg": None, "name": None}
        phone = request.POST.get("phone")
        password = request.POST.get("password")
        phone_test = "^1(3|4|5|6|7|8|9)\d{9}$"
        user1 = Userinfo.objects.filter(phone=phone)
        if user1.count() == 0:
            ret["error_msg"] = "用户不存在"
        elif re.match(phone_test, phone) is None:
            ret["error_msg"] = "请输入正确格式的电话号码"
        elif password != user1.values_list('password', flat=True)[0]:
            ret["error_msg"] = "密码错误，请重新输入"
        else:  # 登录成功
            ret["flag"] = True
            ret["name"] = user1.values_list('name', flat=True)[0]

            # 设置session
            request.session['userid'] = user1.values_list('userid', flat=True)[0]
            request.session['phone'] = phone
            request.session['password'] = password
            request.session['isLogin'] = True
            request.session.set_expiry(0)  # 设置session过期时间(0表示关闭浏览器session失效)
        return HttpResponse(json.dumps(ret))


# ajax注册
@csrf_exempt
def register(request):
    # 前端数据
    ret = {"flag": False, "error_msg": None}
    userid = Userinfo.objects.latest("userid").userid + 1
    data = request.POST
    name = data.get('name')
    phone = data.get('phone')
    age = data.get('age')
    gender = data.get('gender')
    profession = data.get('profession')
    password1 = data.get('password1')
    password2 = data.get('password2')

    age_test = "^(?:[1-9][0-9]?|1[01][0-9]|120)$"  # 年龄在1-120之间
    phone_test = "^1(3|4|5|6|7|8|9)\d{9}$"
    if name == "":
        ret["error_msg"] = "请输入用户名"
    elif age == "":
        ret["error_msg"] = "请输入年龄"
    elif password1 == "" or password2 == "":
        ret["error_msg"] = "密码不能为空，请重新输入密码"
    elif password2 != password1:
        ret["error_msg"] = "两次输入的密码不相同，请重新输入"
    elif re.match(age_test, age) is None:
        ret["error_msg"] = "年龄应在1-120之间"
    elif re.match(phone_test, phone) is None:
        ret["error_msg"] = "请输入正确格式的电话号码"
    else:
        # 数据库数据
        user = Userinfo.objects.filter(phone=phone)
        if user.exists():
            ret["flag"] = False
            ret["error_msg"] = "手机号已存在"
        else:
            user = Userinfo(userid=userid, name=name, password=password1, gender=gender,
                            age=age, profession=profession, phone=phone)
            user.save()
            ret["flag"] = True
    return HttpResponse(json.dumps(ret))


# ajax忘记密码处理
@csrf_exempt
def forget(request):
    ret = {"flag": False, "error_msg": None}
    # 前端数据
    phone = request.POST.get("phone")
    password = request.POST.get("password")
    # 数据库数据
    user = Userinfo.objects.filter(phone=phone)
    if user.exists():
        user.update(password=password)
        ret["flag"] = True
        # return HttpResponse("<script>alert('密码修改成功，请登录！');location.href='/register'</script>")
    else:
        ret["error_msg"] = "手机号不存在"
    return HttpResponse(json.dumps(ret))


# ajax个人信息修改
@csrf_exempt
def profile(request):
    # 前端数据
    ret = {"flag": False, "error_msg": None}
    data = request.POST
    name = data.get('name')
    phone = data.get('phone')
    age = data.get('age')
    gender = data.get('gender')
    profession = data.get('profession')
    password = data.get('password')

    age_test = "^(?:[1-9][0-9]?|1[01][0-9]|120)$"  # 年龄在1-120之间
    if name == "":
        ret["error_msg"] = "请输入用户名"
    elif age == "":
        ret["error_msg"] = "请输入年龄"
    elif password == "":
        ret["error_msg"] = "密码不能为空，请重新输入密码"
    elif re.match(age_test, age) is None:
        ret["error_msg"] = "年龄应在1-120之间"
    else:
        # 数据库数据
        user = Userinfo.objects.filter(phone=phone)
        user.update(name=name, age=age, gender=gender, profession=profession, password=password)
        ret["flag"] = True
    return HttpResponse(json.dumps(ret))


def logout(request):
    request.session.flush()  # 删除一条记录包括(session_key session_data expire_date)三个字段
    return redirect('/')


@csrf_exempt
def discover(request):
    gametag = request.GET.get("tag")
    if gametag == None:
        games11 = Game.objects.all().order_by('?')[:12]
        # return render(request, 'discover.html', {'games11': games11})
    else:
        games11 = Game.objects.filter(tag__icontains=gametag)
    if len(games11) < 9:
        is_paginated = False
    else:
        is_paginated = True
    # 分页显示
    paginator = Paginator(games11, per_page=9)
    page_num = request.GET.get('page', 1)
    try:
        page_num = int(page_num)
    except:
        page_num = 1
    if page_num < 1 or page_num > paginator.num_pages:
        page_num = 1
    # is_paginated = True
    games11_list = paginator.get_page(page_num)
    data = pagination_function(paginator, games11_list, is_paginated)

    # 获取session
    isLogin = False
    if request.session.get('isLogin'):
        isLogin = True
        phone = request.session['phone']
        password = request.session['password']
        user = Userinfo.objects.filter(phone=phone)
        name = user.values_list('name', flat=True)[0]
        age = user.values_list('age', flat=True)[0]
        gender = user.values_list('gender', flat=True)[0]
        profession = user.values_list('profession', flat=True)[0]

    return render(request, 'discover.html', locals())


def ajax_search(request):
    if request.method == 'GET':
        keyword = request.GET.get('keyword', None)
        if keyword:
            count = Game.objects.filter(name__icontains=keyword).count()
            data = {'count': count, }
            return JsonResponse(data)


@csrf_exempt
def game_search(request):
    id_keyword = request.GET.get("id_keyword")
    if id_keyword == None:
        game_list = Game.objects.all().order_by('?')[:12]
    else:
        game_list = Game.objects.filter(name__icontains=id_keyword)

    if len(game_list) < 9:
        is_paginated = False
    else:
        is_paginated = True
    # 分页显示
    paginator = Paginator(game_list, per_page=9)
    page_num = request.GET.get('page', 1)
    try:
        page_num = int(page_num)
    except:
        page_num = 1
    if page_num < 1 or page_num > paginator.num_pages:
        page_num = 1
    # is_paginated = False
    games11_list = paginator.get_page(page_num)
    data = pagination_function(paginator, games11_list, is_paginated)
    return render(request, 'discover.html', locals())


def searchtag(request):
    tag = request.GET['tag']
    games_tag = Game.objects.filter(tag__icontains=tag)
    return render(request, 'discover.html', {"games_tag": games_tag})


def pagination_function(paginator, page, is_paginated=True):
    if not is_paginated:
        # 如果没有分页，则无需显示分页导航条，不用任何分页导航条的数据，因此返回一个空的字典
        return {}

    # 当前页左边连续的页码号，初始值为空
    left = []

    # 当前页右边连续的页码号，初始值为空
    right = []

    # 标示第 1 页页码后是否需要显示省略号
    left_has_more = False

    # 标示最后一页页码前是否需要显示省略号
    right_has_more = False

    # 标示是否需要显示第 1 页的页码号。
    # 因为如果当前页左边的连续页码号中已经含有第 1 页的页码号，此时就无需再显示第 1 页的页码号，
    # 其它情况下第一页的页码是始终需要显示的。
    # 初始值为 False
    first = False

    # 标示是否需要显示最后一页的页码号。
    # 需要此指示变量的理由和上面相同。
    last = False

    # 获得用户当前请求的页码号
    page_number = page.number

    # 获得分页后的总页数
    total_pages = paginator.num_pages

    # 获得整个分页页码列表，比如分了四页，那么就是 [1, 2, 3, 4]
    page_range = paginator.page_range

    if page_number == 1:
        # 如果用户请求的是第一页的数据，那么当前页左边的不需要数据，因此 left=[]（已默认为空）。
        # 此时只要获取当前页右边的连续页码号，
        # 比如分页页码列表是 [1, 2, 3, 4]，那么获取的就是 right = [2, 3]。
        # 注意这里只获取了当前页码后连续两个页码，你可以更改这个数字以获取更多页码。
        right = page_range[page_number:page_number + 2]

        # 如果最右边的页码号比最后一页的页码号减去 1 还要小，
        # 说明最右边的页码号和最后一页的页码号之间还有其它页码，因此需要显示省略号，通过 right_has_more 来指示。
        if right[-1] < total_pages - 1:
            right_has_more = True

        # 如果最右边的页码号比最后一页的页码号小，说明当前页右边的连续页码号中不包含最后一页的页码
        # 所以需要显示最后一页的页码号，通过 last 来指示
        if right[-1] < total_pages:
            last = True

    elif page_number == total_pages:
        # 如果用户请求的是最后一页的数据，那么当前页右边就不需要数据，因此 right=[]（已默认为空），
        # 此时只要获取当前页左边的连续页码号。
        # 比如分页页码列表是 [1, 2, 3, 4]，那么获取的就是 left = [2, 3]
        # 这里只获取了当前页码后连续两个页码，你可以更改这个数字以获取更多页码。
        left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]

        # 如果最左边的页码号比第 2 页页码号还大，
        # 说明最左边的页码号和第 1 页的页码号之间还有其它页码，因此需要显示省略号，通过 left_has_more 来指示。
        if left[0] > 2:
            left_has_more = True

        # 如果最左边的页码号比第 1 页的页码号大，说明当前页左边的连续页码号中不包含第一页的页码，
        # 所以需要显示第一页的页码号，通过 first 来指示
        if left[0] > 1:
            first = True
    else:
        # 用户请求的既不是最后一页，也不是第 1 页，则需要获取当前页左右两边的连续页码号，
        # 这里只获取了当前页码前后连续两个页码，你可以更改这个数字以获取更多页码。
        left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1]
        right = page_range[page_number:page_number + 2]

        # 是否需要显示最后一页和最后一页前的省略号
        if right[-1] < total_pages - 1:
            right_has_more = True
        if right[-1] < total_pages:
            last = True

        # 是否需要显示第 1 页和第 1 页后的省略号
        if left[0] > 2:
            left_has_more = True
        if left[0] > 1:
            first = True

    data = {
        'left': left,
        'right': right,
        'left_has_more': left_has_more,
        'right_has_more': right_has_more,
        'first': first,
        'last': last,
    }

    return data


# 数据库测试
def testdb(request):
    # 字段名需要同数据库中一致
    test1 = Userinfo(UserID="2", name="li", password="123", phone="123123")
    test1.save()
    return HttpResponse('<p>数据添加成功</p>')

@csrf_exempt
def comment_control(request):  # 提交评论的处理函数
    ret = {"flag": False, "error_msg": None}
    if request.session.get("isLogin"):
        num = GameComment.objects.latest("num").num + 1
        comment = request.POST.get('comment')
        gameid = request.POST.get('id')
        userid=request.session['userid']
        gob = 'b'
        s = SnowNLP(comment)
        if s.sentiments > 0.5:
            gob = 'g'
        else:
            gob = 'b'
        test1 = GameComment(num=num, gameid=gameid, comment=comment, gob=gob, userid=userid,
                            score=5*s.sentiments)  # 将提交的数据保存到数据库中
        test1.save()
        ret["flag"] = True
        update_rating(userid, gameid)
    else:
        ret["error_msg"] = "您未登录，请登录后评论"
    return HttpResponse(json.dumps(ret))
